package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
	"xinyuan/copy/models"
)

type CopyController struct {
	beego.Controller
}

func (c *CopyController) GetCopy() {
	uid := c.GetString("uid")
	response := models.CopyResponse{}

	var copyList []*models.Item
	o := orm.NewOrm()
	qs := o.QueryTable(new(models.Item))
	qs.Filter("uid", uid)
	count, e := qs.All(&copyList)
	if e != nil {
		beego.Info("query all ", e.Error())

		response.Code = 400
		response.Data = e.Error()
	} else {
		beego.Info("query all ", count)
		response.Code = 200
		response.Data = copyList
	}

	c.Data["json"] = &response
	c.ServeJSON()
}

func (c *CopyController) PostCopy() {
	uid := c.GetString("uid")
	copyStr := c.GetString("copy")

	beego.Info("uid:", uid, " copy:", copyStr)

	item := models.Item{
		Uid:        uid,
		Msg:        copyStr,
		CreateTime: time.Now(),
	}
	o := orm.NewOrm()
	id, e := o.Insert(&item)
	response := models.CopyResponse{}

	if e != nil {
		response.Code = 400
		response.Data = e.Error()
	} else {
		beego.Info("id:", id)
		response.Code = 200
		response.Data = item
	}

	c.Data["json"] = &response
	c.ServeJSON()
}

func (c *CopyController) DeleteCopy() {
	uid := c.GetString("uid")
	copyId, e := c.GetInt("copyId")
	response := models.CopyResponse{}

	if uid == "" {
		response.Code = 400
		response.Data = "uid error"
	} else {
		if e != nil {
			response.Code = 400
			response.Data = e.Error()
		} else {
			item := models.Item{
				Id: copyId,
			}
			o := orm.NewOrm()
			_, e = o.Delete(&item)

			if e != nil {
				response.Code = 400
				response.Data = e.Error()
			} else {
				response.Code = 200
				response.Data = "delete success"
			}
		}
	}

	c.Data["json"] = &response
	c.ServeJSON()
}
